package com.zr.ssm.controller;

import com.zr.ssm.pojo.Code;
import com.zr.ssm.pojo.Result;
import com.zr.ssm.pojo.User;
import com.zr.ssm.service.UserService;
import com.zr.ssm.utils.JwtUtils;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
//支持跨域
@CrossOrigin
@AllArgsConstructor
@RequestMapping("/api")
public class InitController {

    UserService userService;

    @PostMapping("/reguse")
    public Result register(User user){
        Result result = new Result(0,"register ok");
        Boolean have = userService.selectByUsername(user);
        if (have){
            result.setStatus(1);
            result.setMessage("register fail");
            result.setCode(Code.RegisterFail);
        }
        else {
            Boolean flag = userService.register(user);
            if (flag) {
                result.setCode(Code.RegisterSucc);
            } else {
                result.setStatus(1);
                result.setMessage("register fail");
                result.setCode(Code.RegisterFail);
            }
        }
        return result;
    }

    @PostMapping("/login")
    public Result login(User user){
        Result result = new Result(0,"login ok");
        User loginUser = userService.login(user);
        if (loginUser != null){
            String token =JwtUtils.createToken(loginUser.getId().toString(), loginUser.getUsername());
            result.setToken(token);
        }else{
           result.setStatus(1);
           result.setMessage("login fail");
        }
        return result;
    }
}
